import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:vamos/core/index.dart';
import '../../core/models/user_model.dart';
import '../../core/models/social_post_entity.dart';
import '../../core/store/redux_user_manager.dart';
import '../../core/store/redux_social_manager.dart';

/// 搜索页面
class VamosSearchInterface extends StatefulWidget {
  const VamosSearchInterface({super.key});

  @override
  State<VamosSearchInterface> createState() => _VamosSearchInterfaceState();
}

class _VamosSearchInterfaceState extends State<VamosSearchInterface>
    with TickerProviderStateMixin {
  final TextEditingController _searchController = TextEditingController();
  late TabController _tabController;

  String _searchQuery = '';
  List<UserDataEntity> _searchUsers = [];
  List<SocialPostEntity> _searchPosts = [];
  bool _isSearching = false;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _searchController.addListener(_onSearchChanged);
    _tabController.addListener(_onTabChanged);
  }

  /// 标签切换监听
  void _onTabChanged() {
    setState(() {});
  }

  @override
  void dispose() {
    _searchController.dispose();
    _tabController.dispose();
    super.dispose();
  }

  /// 搜索内容变化监听
  void _onSearchChanged() {
    final query = _searchController.text.trim();
    if (query != _searchQuery) {
      setState(() {
        _searchQuery = query;
        _isSearching = true;
      });
      _performSearch(query);
    }
  }

  /// 执行搜索
  Future<void> _performSearch(String query) async {
    if (query.isEmpty) {
      setState(() {
        _searchUsers = [];
        _searchPosts = [];
        _isSearching = false;
      });
      return;
    }

    try {
      final userManager = serviceLocator<ReduxUserManager>();
      final socialManager = serviceLocator<ReduxSocialManager>();

      // 搜索用户
      final allUsers = userManager.getAllUsers();
      final filteredUsers =
          allUsers.where((user) {
            return user.displayName.toLowerCase().contains(
                  query.toLowerCase(),
                ) ||
                user.personalBio.toLowerCase().contains(query.toLowerCase()) ||
                user.loginAccount.toLowerCase().contains(query.toLowerCase());
          }).toList();

      // 搜索动态
      final allPosts = socialManager.getAllPosts();
      final filteredPosts =
          allPosts.where((post) {
            return post.content.toLowerCase().contains(query.toLowerCase());
          }).toList();

      setState(() {
        _searchUsers = filteredUsers;
        _searchPosts = filteredPosts;
        _isSearching = false;
      });
    } catch (e) {
      setState(() {
        _isSearching = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          top: false,
          bottom: false,
          child: Column(
            children: [
              SizedBox(height: MediaQuery.of(context).padding.top),

              // 顶部栏
              _buildTopBar(),

              SizedBox(height: 20.h),

              // 搜索框
              _buildSearchBar(),

              SizedBox(height: 20.h),

              // 标签页
              _buildTabBar(),

              SizedBox(height: 16.h),

              // 内容区域
              Expanded(
                child: TabBarView(
                  controller: _tabController,
                  children: [_buildCommunityTab(), _buildUserTab()],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部栏
  Widget _buildTopBar() {
    return Container(
      height: 56.h,
      child: Row(
        children: [
          // 返回按钮
          Icon(Icons.arrow_back, size: 26.sp, color: Colors.white)
              .paddingHorizontal(16.w)
              .inkWell(
                onTap: () {
                  Navigator.of(context).pop();
                },
              ),

          // 标题
          Expanded(
            child: Text('Search')
                .fontSize(16.sp)
                .fontFamily(
                  GoogleFonts.goblinOne(fontWeight: FontWeight.w400).fontFamily,
                )
                .textColor(Colors.white)
                .textAlignment(TextAlign.center),
          ),

          // 占位，保持对称
          SizedBox(width: 56.w),
        ],
      ),
    );
  }

  /// 构建搜索框
  Widget _buildSearchBar() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      height: 50.h,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      decoration: BoxDecoration(
        color: const Color(0x51D9D9D9),
        borderRadius: BorderRadius.circular(25.w),
      ),
      child: Row(
        children: [
          // 搜索输入框
          Expanded(
            child: Material(
              color: Colors.transparent,
              child: TextField(
                controller: _searchController,
                decoration: InputDecoration(
                  hintText: 'Search',
                  hintStyle: TextStyle(color: Colors.white, fontSize: 16.sp),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.zero,
                ),
                style: TextStyle(color: Colors.white, fontSize: 16.sp),
                autofocus: true,
              ),
            ),
          ),

          SizedBox(width: 12.w),

          // 搜索按钮
          Image.asset(
            'assets/images/search.png',
            width: 32.w,
            height: 32.w,
          ).inkWell(
            onTap: () {
              _performSearch(_searchController.text.trim());
            },
          ),

          // 清除按钮
          if (_searchQuery.isNotEmpty) ...[
            SizedBox(width: 8.w),
            Icon(Icons.clear, size: 20.w, color: Colors.grey[600]).inkWell(
              onTap: () {
                _searchController.clear();
              },
            ),
          ],
        ],
      ),
    );
  }

  /// 构建标签栏
  Widget _buildTabBar() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        children: [
          // Community 标签
          Expanded(
            child: Column(
              children: [
                Text('Community')
                    .fontSize(16.sp)
                    .textColor(
                      _tabController.index == 0
                          ? const Color(0xFFCEF672)
                          : Colors.white,
                    )
                    .fontFamily(
                      GoogleFonts.protestStrike(
                        fontWeight: FontWeight.w400,
                      ).fontFamily,
                    )
                    .center()
                    .inkWell(
                      onTap: () {
                        _tabController.animateTo(0);
                      },
                    ),

                SizedBox(height: 4.h),

                // 下划线
                if (_tabController.index == 0)
                  Container(
                    height: 2.h,
                    width: 30.w,
                    decoration: BoxDecoration(
                      color: const Color(0xFFCEF672),
                      borderRadius: BorderRadius.circular(1.r),
                    ),
                  ),
              ],
            ),
          ),

          // User 标签
          Expanded(
            child: Column(
              children: [
                Text('User')
                    .fontSize(16.sp)
                    .textColor(
                      _tabController.index == 1
                          ? const Color(0xFFCEF672)
                          : Colors.white,
                    )
                    .fontFamily(
                      GoogleFonts.protestStrike(
                        fontWeight: FontWeight.w400,
                      ).fontFamily,
                    )
                    .center()
                    .inkWell(
                      onTap: () {
                        _tabController.animateTo(1);
                      },
                    ),

                SizedBox(height: 4.h),

                // 下划线
                if (_tabController.index == 1)
                  Container(
                    height: 2.h,
                    width: 30.w,
                    decoration: BoxDecoration(
                      color: const Color(0xFFCEF672),
                      borderRadius: BorderRadius.circular(1.r),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建社区标签页
  Widget _buildCommunityTab() {
    if (_isSearching) {
      return Center(child: CircularProgressIndicator(color: Colors.white));
    }

    if (_searchQuery.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/images/no_data.png',
              width: 120.w,
              height: 120.w,
            ),
            SizedBox(height: 16.h),
            Text('Start typing to search posts')
                .fontSize(16.sp)
                .textColor(Colors.grey[400])
                .textAlignment(TextAlign.center),
          ],
        ),
      );
    }

    if (_searchPosts.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/images/no_data.png',
              width: 120.w,
              height: 120.w,
            ),
            SizedBox(height: 16.h),
            Text('No posts found')
                .fontSize(16.sp)
                .textColor(Colors.grey[400])
                .textAlignment(TextAlign.center),
          ],
        ),
      );
    }

    return ListView.builder(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      itemCount: _searchPosts.length,
      itemBuilder: (context, index) {
        final post = _searchPosts[index];
        return _buildPostItem(post);
      },
    );
  }

  /// 构建用户标签页
  Widget _buildUserTab() {
    if (_isSearching) {
      return Center(child: CircularProgressIndicator(color: Colors.white));
    }

    if (_searchQuery.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/images/no_data.png',
              width: 120.w,
              height: 120.w,
            ),
            SizedBox(height: 16.h),
            Text('Start typing to search users')
                .fontSize(16.sp)
                .textColor(Colors.grey[400])
                .textAlignment(TextAlign.center),
          ],
        ),
      );
    }

    if (_searchUsers.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/images/no_data.png',
              width: 120.w,
              height: 120.w,
            ),
            SizedBox(height: 16.h),
            Text('No users found')
                .fontSize(16.sp)
                .textColor(Colors.grey[400])
                .textAlignment(TextAlign.center),
          ],
        ),
      );
    }

    return ListView.builder(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      itemCount: _searchUsers.length,
      itemBuilder: (context, index) {
        final user = _searchUsers[index];
        return _buildUserItem(user);
      },
    );
  }

  /// 构建动态项
  Widget _buildPostItem(SocialPostEntity post) {
    final userManager = serviceLocator<ReduxUserManager>();
    final author = userManager.getUserById(post.authorId);

    return Column(
      children: [
        Container(
          margin: EdgeInsets.only(top: 6.h, bottom: 6.h),
          child: Row(
            children: [
              // 动态媒体
              SizedBox(
                width: 80.w,
                height: 80.w,
                child: Stack(
                  children: [
                    // 媒体内容
                    if (post.mediaType == PostMediaType.image &&
                        post.mediaUrl != null)
                      Image.asset(
                        post.mediaUrl!,
                        width: 80.w,
                        height: 80.w,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Icon(
                            Icons.image,
                            size: 30.w,
                            color: Colors.grey[600],
                          ).center();
                        },
                      )
                    else if (post.mediaType == PostMediaType.video &&
                        post.thumbnailUrl != null)
                      Image.asset(
                        post.thumbnailUrl!,
                        width: 80.w,
                        height: 80.w,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Icon(
                            Icons.video_library,
                            size: 30.w,
                            color: Colors.grey[600],
                          ).center();
                        },
                      )
                    else
                      Icon(
                        post.mediaType == PostMediaType.video
                            ? Icons.video_library
                            : Icons.image,
                        size: 30.w,
                        color: Colors.grey[600],
                      ).center(),

                    // 视频播放图标
                    if (post.mediaType == PostMediaType.video)
                      Container(
                        width: 80.w,
                        height: 80.w,
                        child:
                            Icon(
                              Icons.play_circle_filled,
                              size: 32.w,
                              color: Colors.white.withOpacity(0.8),
                            ).center(),
                      ),
                  ],
                ),
              ),

              SizedBox(width: 12.w),

              // 动态内容
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 动态内容
                    Text(
                      post.content,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ).fontSize(14.sp).textColor(Colors.white).bold(),

                    SizedBox(height: 8.h),

                    // 作者信息
                    Row(
                      children: [
                        // 作者头像
                        Container(
                          width: 24.w,
                          height: 24.w,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(color: Colors.white, width: 1),
                          ),
                          child: ClipOval(
                            child:
                                author != null
                                    ? Image.asset(
                                      author.profileImage,
                                      width: 24.w,
                                      height: 24.w,
                                      fit: BoxFit.cover,
                                      errorBuilder: (
                                        context,
                                        error,
                                        stackTrace,
                                      ) {
                                        return Icon(
                                          Icons.person,
                                          size: 12.w,
                                          color: Colors.grey[600],
                                        ).center();
                                      },
                                    )
                                    : Icon(
                                      Icons.person,
                                      size: 12.w,
                                      color: Colors.grey[600],
                                    ).center(),
                          ),
                        ),

                        SizedBox(width: 8.w),

                        // 作者信息列
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // 作者名称
                              Text(
                                author?.displayName ?? 'Unknown',
                              ).fontSize(12.sp).textColor(Colors.grey[300]),

                              SizedBox(height: 2.h),

                              // 作者简介
                              Text(
                                author?.personalBio ?? '',
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ).fontSize(10.sp).textColor(Colors.grey[400]),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),

        Divider(color: const Color(0xFFD9D9D9), height: 1),
      ],
    ).inkWell(
      onTap: () {
        // TODO: 导航到动态详情页
      },
    );
  }

  /// 构建用户项
  Widget _buildUserItem(UserDataEntity user) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Row(
        children: [
          // 用户头像
          Container(
            width: 60.w,
            height: 60.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Colors.white, width: 2),
            ),
            child: ClipOval(
              child: Image.asset(
                user.profileImage,
                width: 60.w,
                height: 60.w,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Icon(
                    Icons.person,
                    size: 30.w,
                    color: Colors.grey[600],
                  ).center();
                },
              ),
            ),
          ),

          SizedBox(width: 16.w),

          // 用户信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 用户名
                Text(
                  user.displayName,
                ).fontSize(16.sp).textColor(Colors.white).bold(),

                SizedBox(height: 4.h),

                // 用户简介
                Text(
                  user.personalBio,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ).fontSize(14.sp).textColor(Colors.grey[300]),
              ],
            ),
          ),

          // 查看按钮
          ClipRRect(
            borderRadius: BorderRadius.circular(20.r),
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(20.r),
                  border: Border.all(
                    color: Colors.white.withOpacity(0.3),
                    width: 1,
                  ),
                ),
                child:
                    Text('View').fontSize(12.sp).textColor(Colors.white).bold(),
              ).inkWell(
                onTap: () {
                  // TODO: 导航到用户详情页
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}
